﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using log4net;

namespace Century.EnterpriseLibrary.LogHandler
{
    public static class Loging
    {
        private static readonly List<ILog> LoggerList = Init();
        private static List<ILog> Init()
        {
            string config = "log4net.config";
            StringBuilder sb = new StringBuilder();
            sb.Append(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
            sb.Append(".");
            sb.Append(config);
            Stream configStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(sb.ToString());
            log4net.Config.XmlConfigurator.Configure(configStream);
            log4net.GlobalContext.Properties["host"] = Environment.MachineName;
            return new List<ILog>();
        }
        public static ILog LogWithName(string loggerName)
        {
            if (log4net.ThreadContext.Properties["clientIp"] == null || !string.IsNullOrEmpty(log4net.ThreadContext.Properties["clientIp"].ToString()))
            {
                if (HttpContext.Current != null && HttpContext.Current.Request != null && !string.IsNullOrEmpty(HttpContext.Current.Request.UserHostAddress))
                {
                    log4net.ThreadContext.Stacks["clientIp"].Push(HttpContext.Current.Request.UserHostAddress.PadLeft(15));
                    //log4net.ThreadContext.Properties["clientIp"] = HttpContext.Current.Request.UserHostAddress.PadLeft(15);
                }
                else
                {
                    log4net.ThreadContext.Stacks["clientIp"].Push("Not Web App");

                    log4net.ThreadContext.Properties["clientIp"] = string.Empty;
                }
            }

            if (LoggerList.Count(c => c.Logger.Name == loggerName) > 0)
            {
                return LoggerList.Find(c => c.Logger.Name == loggerName);
            }
            else
            {
                ILog logger = LogManager.GetLogger(loggerName);
                LoggerList.Add(logger);
                
                return logger;
            }
        }

        public static ILog Log
        {
            get
            {
                string loggerName = "MainLogger";
                if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null)
                {
                    loggerName = System.Web.HttpContext.Current.Request.Url.Host;
                }
                else
                {
                    loggerName = Process.GetCurrentProcess().ProcessName.Replace(".exe", string.Empty).Replace(".vshost", string.Empty);
                }
                if (LoggerList.Count(c => c.Logger.Name == loggerName) > 0)
                {
                    return LoggerList.Find(c => c.Logger.Name == loggerName);
                }
                else
                {
                    ILog logger = LogManager.GetLogger(loggerName);
                    LoggerList.Add(logger);

                    log4net.Repository.Hierarchy.Hierarchy hier =
                    log4net.LogManager.GetLoggerRepository() as log4net.Repository.Hierarchy.Hierarchy;

                    if (hier != null)
                    {
                        //get ADONetAppender
                        log4net.Appender.AdoNetAppender adoAppender =
                           (log4net.Appender.AdoNetAppender)hier.GetLogger(loggerName).Repository.GetAppenders().FirstOrDefault(c => c.Name == "AdoNetAppender");
                        if (adoAppender != null)
                        {
                            adoAppender.ConnectionString = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
                            adoAppender.ActivateOptions(); //refresh settings of appender
                        }
                    }
                    return logger;
                }

            }
        }
    }
}